package club.gskj.gulimall.order.service.impl;

import club.gskj.common.exception.NoStockException;
import club.gskj.common.to.mq.OrderTo;
import club.gskj.common.to.mq.SeckillOrderTO;
import club.gskj.common.utils.R;
import club.gskj.common.vo.MemberRespVo;
import club.gskj.gulimall.order.constant.OrderConstant;
import club.gskj.gulimall.order.entity.OrderItemEntity;
import club.gskj.gulimall.order.entity.PaymentInfoEntity;
import club.gskj.gulimall.order.enume.OrderStatusEnum;
import club.gskj.gulimall.order.feign.CartFeignService;
import club.gskj.gulimall.order.feign.MemberFeignService;
import club.gskj.gulimall.order.feign.ProductFeignService;
import club.gskj.gulimall.order.feign.WareFeignService;
import club.gskj.gulimall.order.interceptor.UserLoginInterceptor;
import club.gskj.gulimall.order.service.PaymentInfoService;
import club.gskj.gulimall.order.to.OrderCreateTo;
import club.gskj.gulimall.order.vo.*;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.attoparser.dom.INode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import club.gskj.common.utils.PageUtils;
import club.gskj.common.utils.Query;

import club.gskj.gulimall.order.dao.OrderDao;
import club.gskj.gulimall.order.entity.OrderEntity;
import club.gskj.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("omsOrderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private CartFeignService cartFeignService;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private OrderItemServiceImpl orderItemService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private PaymentInfoService paymentInfoService;

    private ThreadLocal<OrderSubmitVo> threadLocal = new ThreadLocal<>();

    /**
     * 同一个对象内事务方法互调默认失效，原因是绕过了代理对象
     * 事务使用代理对象来控制
     */
    @Transactional(timeout = 30)// a事务的所有设置都会传播到和他公用一个事务的方法
    public void a() {
        // b、c做任何设置都没用，都是和a共用一个事务
//        this.b();
//        this.c();

        // 获取代理对象
        OrderServiceImpl orderService = (OrderServiceImpl) AopContext.currentProxy();
        // 通过代理对象直接调用本类方法,这样每个方法设置的事务才能生效
        orderService.b();
        orderService.c();

        //bService.b(); a事务
        //cService.c(); 新事务(不会回滚)
    }

    @Transactional(propagation = Propagation.REQUIRED, timeout = 2)
    public void b() {
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, timeout = 10)
    public void c() {
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        OrderConfirmVo confirmVO = new OrderConfirmVo();

        // 登录用户信息
        MemberRespVo memberRespVo = UserLoginInterceptor.local.get();

        // 在当前主线程中获取 Request信息,并存入到子线程中， 默认使用异步线程时无法共享 ThreadLocal中的本地数据。
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 异步调用
        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
            // 在子线程中存入 主线程中的Request信息，保证请求对象信息同步
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVO.setAddress(address);
        }, threadPoolExecutor);

        // 异步调用
        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);

            // 查询用户的所有购物项
            List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
            // feign在远程调用时会构造请求，会调用很多拦截器，
            // RequestInterceptor rep
            confirmVO.setItems(currentUserCartItems);
        }, threadPoolExecutor).thenRunAsync(() -> {
            // 继续执行查询商品库存
            List<OrderItemVo> itme = confirmVO.getItems();

            List<Long> collect = itme.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

            R r = wareFeignService.hasStockBySku(collect);
            if (r.getCode() == 0) {
                List<SkuStockVo> data = r.getData(new TypeReference<List<SkuStockVo>>() {
                });
                if (data != null) {
                    Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSpuId, SkuStockVo::getHasStock));
                    confirmVO.setHasStock(map);
                }
            }
        }, threadPoolExecutor);

        // 用户积分
        confirmVO.setIntegration(memberRespVo.getIntegration());

        // token防重机制
        String token = UUID.randomUUID().toString().replace("-", "");

        // token存入 页面
        confirmVO.setOrderToken(token);
        // token 存入 redis，过期时间30分钟
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);

        // 阻塞等待所有线程完成
        CompletableFuture.allOf(addressFuture, cartFuture).get();
        return confirmVO;
    }

    /***
     * 本地事务；在分布式系统中，只能控制自己的回滚，控制不了其他服务的回滚
     *  分布式事务，最大原因  ， 网络问题+分布式机器
     *
     *  isolation = Isolation.REPEATABLE_READ, 设置事务隔离级别
     *  propagation = Propagation.REQUIRED 设置事务传播行为
     *
     *  @GlobalTransactional： 开启seata全局事务管理
     */
//    @GlobalTransactional seata分布式事务，对大并发性能会低下，不推荐使用
    @Transactional(rollbackFor = Exception.class)
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {
        threadLocal.set(vo);

        // 登录用户信息
        MemberRespVo memberRespVo = UserLoginInterceptor.local.get();

        SubmitOrderResponseVo submitOrderResponseVo = new SubmitOrderResponseVo();
        // 默认0 为创建订单成功
        submitOrderResponseVo.setCode(0);

        // 1.验证临牌【令牌验证、对比、删除 必须是原子性操作】
        String orderToken = vo.getOrderToken();

        // lua 脚本
        // 返回值 0 key不存在、 key无法删除
        // 返回值 1 成功删除key

        String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
//             验证token是否一致、
//        if (redisOrderToken != null && redisOrderToken.equals(orderToken)) {
//             令牌验证通过
//            submitOrderResponseVo.setCode(0);
//            stringRedisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//        }

        // 原子性验证token是否一致、调用 redis lua脚本
        Long execute = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        // 验证成功,开始创建订单信息
        if (execute.intValue() == 1) {
            // 创建订单信息
            OrderCreateTo orderCreate = createOrder();
            // 商品验价
            // 页面价格
            BigDecimal payPrice = vo.getPayPrice();
            // 计算价格
            BigDecimal payAmount = orderCreate.getOrder().getPayAmount();
            // 计算绝对值，小于0.01即为验价成功
            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) <= 0.01) {
                // 金额对比成功
                // 保存订单到数据库
                saveOrderToDB(orderCreate);

                // 锁定商品库存,有异常就会滚事务
                // 参数： 订单号、订单项、
                WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();

                wareSkuLockVo.setOrderSn(orderCreate.getOrder().getOrderSn());
                List<OrderItemVo> itemVo = orderCreate.getOrderItemList().stream().map(item -> {

                    OrderItemVo orderItemVo = new OrderItemVo();
                    orderItemVo.setSkuId(item.getSkuId());
                    orderItemVo.setCount(item.getSkuQuantity());
                    orderItemVo.setTitle(item.getSkuName());
                    return orderItemVo;
                }).collect(Collectors.toList());
                wareSkuLockVo.setOrderItems(itemVo);

                // 调用远程服务 锁定商品库存数量
                R r = wareFeignService.orderLockStock(wareSkuLockVo);
                if (r.getCode() == 0) {
                    // 获取当前订单信息
                    submitOrderResponseVo.setOrderEntity(orderCreate.getOrder());
                    // TODO 积分服务抛出异常
//                    int i = 1 / 0;

                    // 订单常见成功，发送消息给MQ
                    rabbitTemplate.convertAndSend("order-event-exchange", "order-create-order", orderCreate.getOrder());

                    return submitOrderResponseVo;
                } else {
                    submitOrderResponseVo.setCode(3);
                    // 获取库存的id
                    Long skuId = r.getData(new TypeReference<Long>() {
                    });
                    throw new NoStockException(skuId);
                }
            } else {
                // 价格对比失败
                submitOrderResponseVo.setCode(2);
                return submitOrderResponseVo;
            }
        }
        // 失败
        submitOrderResponseVo.setCode(1);
        return submitOrderResponseVo;
    }

    @Override
    public OrderEntity getOrderStatusByOrderSn(String orderSn) {

        OrderEntity orderEntity = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return orderEntity;
    }

    /**
     * 定时关闭订单操作
     *
     * @param orderEntity
     */
    @Override
    public void orderClose(OrderEntity orderEntity) {
        // 查询当前订单的状态
        OrderEntity orderDb = this.baseMapper.selectById(orderEntity.getId());
        // 判断关单条件： 待付款状态
        if (orderDb.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            OrderEntity updateOrder = new OrderEntity();
            updateOrder.setStatus(OrderStatusEnum.CANCLED.getCode());
            updateOrder.setId(orderDb.getId());
            this.baseMapper.updateById(updateOrder);

            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderDb, orderTo);
            // 发送消息到MQ
            try {
                // 一定必须保证消息成功发送出去，每一个发送的消息都做好日志记录
                // (数据库保存要发送的消息，定时扫描数据库将发送失败的消息重新发送)
                rabbitTemplate.convertAndSend("order-event-exchange", "order-release-other", orderTo);
            } catch (Exception e) {
                // 将发送失败的消息重试发送...
            }
        }
    }

    @Override
    public PayVo getOrderPayInfoByOrderSn(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = getOrderStatusByOrderSn(orderSn);

        // 查询订单的所有订单项
        List<OrderItemEntity> list = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));

        // 订单金额处理，保留两位数、向上取整
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);

        String skuName = list.get(0).getSkuName();
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());
        payVo.setSubject(skuName);
        payVo.setBody(list.get(0).getSkuAttrsVals());

        return payVo;
    }

    @Override
    public PageUtils queryPageWithItems(Map<String, Object> params) {
        // 从拦截器中获取 登陆用户信息
        MemberRespVo memberRespVo = UserLoginInterceptor.local.get();
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                        .eq("member_id", memberRespVo.getId())
                        .orderByDesc("id")
        );

        // 重新封装订单，
        List<OrderEntity> collect = page.getRecords().stream().map(item -> {
            // 查询订单的所有订单项
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", item.getOrderSn()));
            item.setItemEntities(itemEntities);
            return item;
        }).collect(Collectors.toList());
        page.setRecords(collect);

        return new PageUtils(page);
    }

    @Override
    public String handlePayResult(PayAsyncVo payAsyncVo) {
        // 保存交易流水
        PaymentInfoEntity info = new PaymentInfoEntity();
        info.setAlipayTradeNo(payAsyncVo.getTrade_no());
        info.setOrderSn(payAsyncVo.getOut_trade_no());
        info.setPaymentStatus(payAsyncVo.getTrade_status());
        info.setCallbackTime(payAsyncVo.getNotify_time());
        paymentInfoService.save(info);

        // 修改订单状态
        String trade_status = payAsyncVo.getTrade_status();
        if ("TRADE_SUCCESS ".equals(trade_status) || "TRADE_FINISHED ".equals(trade_status)) {
            //  订单号
            String out_trade_no = payAsyncVo.getOut_trade_no();
            this.baseMapper.updateOrderStatus(out_trade_no, OrderStatusEnum.PAYED.getCode());
        }
        return null;
    }

    @Override
    public void createSeckillOrder(SeckillOrderTO orderEntity) {
        // TODO 保存订单信息
        OrderEntity order = new OrderEntity();
        order.setOrderSn(orderEntity.getOrderSn());
        order.setMemberId(orderEntity.getMemberId());
        order.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal seckillPrice = orderEntity.getSeckillPrice().multiply(new BigDecimal(orderEntity.getNum() + ""));
        order.setPayAmount(seckillPrice);
        this.save(order);

        // TODO 保存订单项信息
        OrderItemEntity itemEntity = new OrderItemEntity();
        itemEntity.setOrderSn(order.getOrderSn());
        itemEntity.setRealAmount(seckillPrice);
        itemEntity.setSkuQuantity(orderEntity.getNum());
        orderItemService.save(itemEntity);
    }

    /***
     *  保存订单信息到数据库
     */
    private void saveOrderToDB(OrderCreateTo orderCreate) {
        OrderEntity order = orderCreate.getOrder();
        // 保存订单信息到数据库
        order.setModifyTime(new Date());
        this.save(order);

        List<OrderItemEntity> orderItemList = orderCreate.getOrderItemList();
        // 保存订单项数据
        orderItemService.saveBatch(orderItemList);
    }

    /***
     *  创建订单方法
     */
    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 构建订单信息
        OrderEntity orderEntity = buildOrder();

        // 获取到所有订单项
        List<OrderItemEntity> orderItem = buildOrderItems(orderEntity.getOrderSn());

        // 设置订单
        orderCreateTo.setOrder(orderEntity);

        // 设置订单项
        orderCreateTo.setOrderItemList(orderItem);

        // 计算商品价格
        computePrice(orderEntity, orderItem);
        return orderCreateTo;
    }

    /**
     * 计算价格
     *
     * @param orderEntity 商品信息
     * @param orderItem   商品项信息
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItem) {

        // 订单的总额
        BigDecimal totalPrice = new BigDecimal("0");
        // 优惠卷总额
        BigDecimal totalCoupon = new BigDecimal("0");
        // 积分优惠总额
        BigDecimal totalIntegration = new BigDecimal("0");
        //打折促销总额
        BigDecimal totalPromtion = new BigDecimal("0");
        // 总积分
        BigDecimal totalGiftIntegration = new BigDecimal("0");
        // 总成长值
        BigDecimal totalGiftGrowth = new BigDecimal("0");

        for (OrderItemEntity orderItemEntity : orderItem) {
            // 跌加每一项的总金额，计算全部商品的应付价格
            totalPrice = totalPrice.add(orderItemEntity.getRealAmount());
            // 优惠卷金额
            totalCoupon = totalCoupon.add(orderItemEntity.getCouponAmount());
            // 积分金额
            totalIntegration = totalIntegration.add(orderItemEntity.getIntegrationAmount());
            // 打折金额
            totalPromtion = totalPromtion.add(orderItemEntity.getPromotionAmount());
            // 积分值
            Integer giftIntegration = orderItemEntity.getGiftIntegration();
            totalGiftIntegration = totalGiftIntegration.add(new BigDecimal(giftIntegration.toString()));
            // 成长值
            Integer giftGrowth = orderItemEntity.getGiftGrowth();
            totalGiftGrowth = totalGiftGrowth.add(new BigDecimal(totalGiftGrowth.toString()));
        }
        // 订单总额
        orderEntity.setTotalAmount(totalPrice);
        orderEntity.setCouponAmount(totalCoupon);
        orderEntity.setIntegrationAmount(totalIntegration);
        orderEntity.setPromotionAmount(totalPrice);
        // 应付总额
        orderEntity.setPayAmount(totalPrice.add(orderEntity.getFreightAmount()));
        //订单状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        // 积分、成长值
        orderEntity.setIntegration(totalGiftIntegration.intValue());
        orderEntity.setGrowth(totalGiftGrowth.intValue());
        // 订单状态
        // 默认未删除
        orderEntity.setDeleteStatus(0);
    }

    /***
     *  构建订单信息
     * @return
     */
    private OrderEntity buildOrder() {
        OrderSubmitVo orderSubmitVo = threadLocal.get();
        MemberRespVo memberRespVo = UserLoginInterceptor.local.get();

        // 收货地址id
        Long addrId = orderSubmitVo.getAddrId();

        // 订单信息
        OrderEntity orderEntity = new OrderEntity();

        // 生成订单号
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);

        // 会员id
        orderEntity.setMemberId(memberRespVo.getId());

        // 获取收货地址运费
        R freightById = wareFeignService.getFreightById(addrId);
        if (freightById.getCode() == 0) {
            FreightAddrVo freightAddrVo = freightById.getData(new TypeReference<FreightAddrVo>() {
            });
            if (freightAddrVo != null) {
                // 运费
                BigDecimal freight = freightAddrVo.getFreight();
                // 城市
                String city = freightAddrVo.getMemberAddressVo().getCity();
                // 详细地址
                String detailAddress = freightAddrVo.getMemberAddressVo().getDetailAddress();
                // 收件人名称
                String name = freightAddrVo.getMemberAddressVo().getName();
                // 收件人手机号
                String phone = freightAddrVo.getMemberAddressVo().getPhone();
                // 邮编
                String postCode = freightAddrVo.getMemberAddressVo().getPostCode();
                // 省区
                String province = freightAddrVo.getMemberAddressVo().getProvince();
                //区域
                String region = freightAddrVo.getMemberAddressVo().getRegion();

                // 设置收货人信息
                orderEntity.setReceiverCity(city);
                orderEntity.setReceiverDetailAddress(detailAddress);
                orderEntity.setReceiverName(name);
                orderEntity.setReceiverPhone(phone);
                orderEntity.setReceiverPostCode(postCode);
                orderEntity.setReceiverRegion(region);
                orderEntity.setFreightAmount(freight);
            }
        }
        return orderEntity;
    }

    /***
     *  构建订单项信息
     */
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 获取当前登陆用户购物车的购物项
        // 最后一次确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();

        List<OrderItemEntity> itemEntities = null;
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            itemEntities = currentUserCartItems.stream().map(item -> {
                OrderItemEntity orderItemEntity = buildOrderItem(item);
                orderItemEntity.setOrderSn(orderSn);
                // 构建订单项信息
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return itemEntities;
    }

    /***
     *  构建每一项 订单项信息
     */
    private OrderItemEntity buildOrderItem(OrderItemVo item) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();

        // 1.订单信息，订单id、 订单编号，已做处理

        // 2. 商品spu信息
        R spuInfoBySkuId = productFeignService.getSpuInfoBySkuId(item.getSkuId());
        if (spuInfoBySkuId.getCode() == 0) {
            SpuInfoVo spuInfoVo = spuInfoBySkuId.getData(new TypeReference<SpuInfoVo>() {
            });
            // spu id
            orderItemEntity.setSpuId(spuInfoVo.getId());
            // 商品名称
            orderItemEntity.setSpuName(spuInfoVo.getSpuName());
            // 商品品牌id
            orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
            // 商品分类id
            orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());
        }

        // 3. 商品sku信息
        // skuId
        orderItemEntity.setSkuId(item.getSkuId());
        // 商品名称
        orderItemEntity.setSkuName(item.getTitle());
        // 商品图片
        orderItemEntity.setSkuPic(item.getImage());
        // 商品价格
        orderItemEntity.setSkuPrice(item.getPrice());
        List<String> skuAttrs = item.getSkuAttrs();
        // 将数组分割为 字符串，并以指定符号连接
        String skuAttr = StringUtils.collectionToDelimitedString(skuAttrs, ";");
        // 商品销售属性组合
        orderItemEntity.setSkuAttrsVals(skuAttr);
        // 商品数量
        orderItemEntity.setSkuQuantity(item.getCount());

        // 4. 商品优惠信息(不做处理)

        // 5. 积分信息
        //赠送成长值
        orderItemEntity.setGiftGrowth(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());
        //赠送积分
        orderItemEntity.setGiftIntegration(item.getPrice().multiply(new BigDecimal(item.getCount().toString())).intValue());

        // 价格信息
        // 商品促销分解金额
        orderItemEntity.setPromotionAmount(new BigDecimal("0.0"));
        // 优惠券优惠分解金额
        orderItemEntity.setCouponAmount(new BigDecimal("0.0"));
        // 积分优惠分解金额
        orderItemEntity.setIntegrationAmount(new BigDecimal("0.0"));

        // 原来的价格。没有使用什么优惠信息
        BigDecimal originPrice = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        // TODO 目前优惠价格写死，后期可以调用其他服务查询
        originPrice.subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount());

        // 实际价格:已经除去 商品单价*商品数量各种优惠会的价格
        orderItemEntity.setRealAmount(originPrice);
        return orderItemEntity;
    }
}
